import {
	setStorage,
	getStorage,
	removeStorage
} from "@/util/auth";
import {
	getAuthorize,
	getLocation
} from '@/util/util.js'
import Vue from "vue";
const state = {
	position: getStorage('position'),
}
const mutations = {
	SET_POSITION(state, position) {
		if (position === null) {
			removeStorage('position');
		} else {
			setStorage('position', position)
		}
		state.position = position;
		uni.$emit('position', position)
	}
}
const actions = {
	getPosition({
		commit
	}) {
		return new Promise(async (resolve, reject) => {

			// #ifndef APP
			await getAuthorize('scope.userLocation', '定位')
			// #endif
			try {
				const position = await getLocation()
				const latitude = position.latitude;
				const longitude = position.longitude;
				const location = {
					latitude,
					longitude
				};
				commit('SET_POSITION', location);
				resolve(location)
			} catch (defaultLocation) {
				// 如果获取位置失败，使用默认的位置
				commit('SET_POSITION', defaultLocation);
				resolve(defaultLocation)
			}
		})
	},
}
export default {
	namespaced: true,
	state,
	mutations,
	actions
}